import {
  ModuleFields,
  TextField,
  BooleanField,
  ColorField,
  ChoiceField,
  ImageField,
  FieldGroup,
} from '@hubspot/cms-components/fields';

// ─── CSS ─────────────────────────────────────────────────────────────────────

const css = `
  .qh * { box-sizing: border-box; }
  .qh { font-family: system-ui, -apple-system, sans-serif; }

  .qh-wrap {
    background: var(--qh-bg);
    border-bottom: var(--qh-border);
    max-width: 800px;
    margin: 0 auto;
    padding: 24px 32px 20px;
  }

  .qh-logo-wrap { margin-bottom: 20px; }
  .qh-logo      { width: auto; max-width: 100%; object-fit: contain; display: block; }
  .qh-logo-text { font-size: 18px; font-weight: 800; color: var(--qh-primary); }

  .qh-body {
    display: flex;
    gap: 40px;
    align-items: flex-start;
    flex-wrap: wrap;
  }

  .qh-doc-meta { flex: 1; min-width: 160px; }

  .qh-doc-title {
    font-size: 18px; font-weight: 900; color: #1e293b;
    letter-spacing: 2px; text-transform: uppercase; margin: 0 0 12px;
  }

  .qh-row {
    display: flex; align-items: baseline; gap: 8px;
    font-size: 13px; margin-bottom: 5px;
  }
  .qh-row-label { color: #94a3b8; font-weight: 600; min-width: 80px; flex-shrink: 0; }
  .qh-row-value { color: #1e293b; font-weight: 500; }

  .qh-parties { display: flex; gap: 32px; flex-wrap: wrap; padding-top: 2px; }
  .qh-party   { min-width: 130px; }

  .qh-party-label {
    font-size: 10px; font-weight: 700; letter-spacing: 1.5px;
    text-transform: uppercase; color: #94a3b8; margin: 0 0 6px;
  }
  .qh-party-name { font-size: 14px; font-weight: 700; color: #1e293b; margin: 0 0 2px; }
  .qh-party-sub  { font-size: 12px; color: #64748b; margin: 0 0 2px; }
`;

// ─── Component ───────────────────────────────────────────────────────────────

export function Component({ fieldValues, hublData }: any) {
  const primary        = fieldValues?.styles?.primary?.color || hublData?.brandPrimary || '#6366f1';
  const bg             = fieldValues?.styles?.bg?.color      || '#ffffff';
  const showBorder     = String(fieldValues?.styles?.showBorder) !== 'false';

  const logoPos        = fieldValues?.content?.logoPos        || 'left';
  const logoSize       = fieldValues?.content?.logoSize       || 'medium';
  const logoOverride   = fieldValues?.content?.logoUrl?.src    || null;
  const docTitle       = fieldValues?.content?.docTitle       || 'Quote';
  const showRef        = String(fieldValues?.content?.showRef)        !== 'false';
  const refLabel       = fieldValues?.content?.refLabel               || 'Reference';
  const showIssueDate  = String(fieldValues?.content?.showIssueDate)  !== 'false';
  const issueDateLabel = fieldValues?.content?.issueDateLabel         || 'Date';
  const showExpiry     = String(fieldValues?.content?.showExpiry)     !== 'false';
  const expiryLabel    = fieldValues?.content?.expiryLabel            || 'Valid until';
  const showPrepFor    = String(fieldValues?.content?.showPrepFor)    !== 'false';
  const showPrepBy     = String(fieldValues?.content?.showPrepBy)     !== 'false';

  const quoteNumber    = hublData?.quoteNumber    || null;
  const issueDate      = hublData?.issueDate      || null;
  const expirationDate = hublData?.expirationDate || null;
  const locale         = hublData?.locale         || 'en';
  const buyerCompany   = hublData?.buyerCompany   || null;
  const buyerFirstName = hublData?.buyerFirstName || null;
  const buyerLastName  = hublData?.buyerLastName  || null;
  const senderFirstName = hublData?.senderFirstName || null;
  const senderLastName  = hublData?.senderLastName  || null;
  const senderEmail     = hublData?.senderEmail     || null;
  const senderCompany   = hublData?.senderCompany   || null;
  const senderLogoUrl   = hublData?.senderLogoUrl   || null;

  const logoUrl    = logoOverride || senderLogoUrl || null;
  const buyerName  = [buyerFirstName, buyerLastName].filter(Boolean).join(' ');
  const senderName = [senderFirstName, senderLastName].filter(Boolean).join(' ');

  const fmtDate = (ts: number) =>
    new Date(ts).toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' });

  const logoJustify: Record<string, string> = { left: 'flex-start', center: 'center', right: 'flex-end' };
  const LOGO_HEIGHTS: Record<string, number | 'auto'> = {
    original:  'auto',
    small:     50,
    medium:    100,
    large:     150,
    xlarge:    200,
    humongous: 400,
  };
  const logoHeight = LOGO_HEIGHTS[logoSize] ?? 100;

  const hasLogo    = logoUrl || senderCompany;
  const hasDocMeta = showRef || showIssueDate || showExpiry;
  const hasPrepFor = showPrepFor && !!(buyerCompany || buyerName);
  const hasPrepBy  = showPrepBy  && !!senderName;

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div
        className="qh"
        style={{
          ['--qh-primary' as any]: primary,
          ['--qh-bg' as any]:      bg,
          ['--qh-border' as any]:  showBorder ? '1px solid #e2e8f0' : 'none',
        }}
      >
        <div className="qh-wrap">

          {/* Logo */}
          {hasLogo && (
            <div
              className="qh-logo-wrap"
              style={{ display: 'flex', justifyContent: logoJustify[logoPos] || 'flex-start' }}
            >
              {logoUrl
                ? <img
                    src={logoUrl}
                    alt={senderCompany || ''}
                    className="qh-logo"
                    style={{ height: logoHeight === 'auto' ? 'auto' : logoHeight }}
                  />
                : <span className="qh-logo-text">{senderCompany}</span>
              }
            </div>
          )}

          {/* Body: document metadata + parties */}
          {(hasDocMeta || hasPrepFor || hasPrepBy) && (
            <div className="qh-body">

              {hasDocMeta && (
                <div className="qh-doc-meta">
                  <h2 className="qh-doc-title">{docTitle}</h2>
                  {showRef && quoteNumber && (
                    <div className="qh-row">
                      <span className="qh-row-label">{refLabel}</span>
                      <span className="qh-row-value">{quoteNumber}</span>
                    </div>
                  )}
                  {showIssueDate && issueDate && (
                    <div className="qh-row">
                      <span className="qh-row-label">{issueDateLabel}</span>
                      <span className="qh-row-value">{fmtDate(issueDate)}</span>
                    </div>
                  )}
                  {showExpiry && expirationDate && (
                    <div className="qh-row">
                      <span className="qh-row-label">{expiryLabel}</span>
                      <span className="qh-row-value">{fmtDate(expirationDate)}</span>
                    </div>
                  )}
                </div>
              )}

              {(hasPrepFor || hasPrepBy) && (
                <div className="qh-parties">
                  {hasPrepFor && (
                    <div className="qh-party">
                      <p className="qh-party-label">Prepared for</p>
                      {buyerCompany && <p className="qh-party-name">{buyerCompany}</p>}
                      {buyerName    && <p className="qh-party-sub">{buyerName}</p>}
                    </div>
                  )}
                  {hasPrepBy && (
                    <div className="qh-party">
                      <p className="qh-party-label">Prepared by</p>
                      <p className="qh-party-name">{senderName}</p>
                      {senderCompany && <p className="qh-party-sub">{senderCompany}</p>}
                      {senderEmail   && <p className="qh-party-sub">{senderEmail}</p>}
                    </div>
                  )}
                </div>
              )}

            </div>
          )}

        </div>
      </div>
    </>
  );
}

// ─── Fields ──────────────────────────────────────────────────────────────────

export const fields = (
  <ModuleFields>
    <FieldGroup name="content" label="Content">
      <ImageField
        name="logoUrl"
        label="Logo image"
        helpText="Overrides the auto-resolved logo. Leave blank to use the brand kit or CRM sender logo."
      />
      <ChoiceField
        name="logoPos"
        label="Logo position"
        choices={[['left', 'Left'], ['center', 'Center'], ['right', 'Right']]}
        default="left"
      />
      <ChoiceField
        name="logoSize"
        label="Logo size"
        choices={[
          ['original',  'Original (natural size)'],
          ['small',     'Small (50px)'],
          ['medium',    'Medium (100px)'],
          ['large',     'Large (150px)'],
          ['xlarge',    'X-Large (200px)'],
          ['humongous', 'Humongous (400px)'],
        ]}
        default="medium"
      />
      <TextField    name="docTitle"       label="Document type label"  default="Quote"       helpText="e.g. Quote, Proposal, Offer" />
      <BooleanField name="showRef"        label="Show quote reference" default={true} />
      <TextField    name="refLabel"       label="Reference label"      default="Reference" />
      <BooleanField name="showIssueDate"  label="Show issue date"      default={true} />
      <TextField    name="issueDateLabel" label="Issue date label"     default="Date" />
      <BooleanField name="showExpiry"     label="Show expiry date"     default={true} />
      <TextField    name="expiryLabel"    label="Expiry date label"    default="Valid until" />
      <BooleanField name="showPrepFor"    label="Show 'Prepared for'"  default={true} />
      <BooleanField name="showPrepBy"     label="Show 'Prepared by'"   default={true} />
    </FieldGroup>
    <FieldGroup name="styles" label="Styles" tab="STYLE">
      <ColorField   name="primary"    label="Accent colour"      default={{ color: '', opacity: 100 }} helpText="Leave blank to use brand colour" />
      <ColorField   name="bg"         label="Background colour"  default={{ color: '#ffffff', opacity: 100 }} />
      <BooleanField name="showBorder" label="Show bottom border" default={true} />
    </FieldGroup>
  </ModuleFields>
);

// ─── Meta ─────────────────────────────────────────────────────────────────────

export const meta = {
  label: 'Quote Header',
  content_types: ['QUOTE', 'QUOTE_BLUEPRINT'],
};

// ─── hublDataTemplate ────────────────────────────────────────────────────────

export const hublDataTemplate = `
  {% if quoteTemplateContext.buyerCompany %}
    {% set bc = quoteTemplateContext.buyerCompany %}
  {% endif %}

  {% if quoteTemplateContext.buyerContacts|length > 0 %}
    {% set contact = quoteTemplateContext.buyerContacts[0] %}
  {% endif %}

  {# Quote-level logo > brand kit primary logo > CRM sender logo > empty #}
  {% set resolvedLogoUrl = quoteTemplateContext.quote.hs_logo_url if quoteTemplateContext.quote.hs_logo_url else brand_settings.primaryLogo.src if brand_settings.primaryLogo.src else quoteTemplateContext.quote.hs_sender_company_image_url %}

  {% set hublData = {
    "quoteNumber":     quoteTemplateContext.quote.hs_quote_number,
    "issueDate":       quoteTemplateContext.quote.hs_createdate,
    "expirationDate":  quoteTemplateContext.quote.hs_expiration_date,
    "locale":          quoteTemplateContext.quote.hs_locale,
    "buyerCompany":    bc.name,
    "buyerFirstName":  contact.firstname,
    "buyerLastName":   contact.lastname,
    "senderFirstName": quoteTemplateContext.quote.hs_sender_firstname,
    "senderLastName":  quoteTemplateContext.quote.hs_sender_lastname,
    "senderEmail":     quoteTemplateContext.quote.hs_sender_email,
    "senderCompany":   quoteTemplateContext.quote.hs_sender_company_name,
    "senderLogoUrl":   resolvedLogoUrl,
    "brandPrimary":    brand_settings.primaryColor.hex
  } %}
`;
